<template>
  <div :class="{fullscreen:fullscreen}" class="tinymce-container" :style="{width:containerWidth}">
    <textarea :id="tinymceId" class="tinymce-textarea" />
  </div>
</template>

<script>
import Global from '@/../public/js/global'
import { fileHostUrl } from '@/utils'
import { ParamArr } from '@/../public/js/paramarr'
import plugins from './plugins'
import toolbar from './toolbar'
import { RPAAddCommunityFile } from '@/api/blog'
// 引入tinymce富文本
import tinymce from 'tinymce'
import 'tinymce/themes/silver/theme'
import 'tinymce/icons/default'
// 引入tinymce富文本插件
import 'tinymce/plugins/advlist'
import 'tinymce/plugins/anchor'
import 'tinymce/plugins/autolink'
import 'tinymce/plugins/autosave'
import 'tinymce/plugins/code'
import 'tinymce/plugins/codesample'
import 'tinymce/plugins/colorpicker'
import 'tinymce/plugins/contextmenu'
import 'tinymce/plugins/directionality'
import 'tinymce/plugins/emoticons'
import 'tinymce/plugins/emoticons/js/emojis.min'
import 'tinymce/plugins/fullscreen'
import 'tinymce/plugins/hr'
import 'tinymce/plugins/image'
import 'tinymce/plugins/imagetools'
import 'tinymce/plugins/insertdatetime'
import 'tinymce/plugins/link'
import 'tinymce/plugins/lists'
import 'tinymce/plugins/media'
import 'tinymce/plugins/nonbreaking'
import 'tinymce/plugins/noneditable'
import 'tinymce/plugins/pagebreak'
import 'tinymce/plugins/paste'
import 'tinymce/plugins/preview'
import 'tinymce/plugins/print'
import 'tinymce/plugins/save'
import 'tinymce/plugins/searchreplace'
import 'tinymce/plugins/spellchecker'
import 'tinymce/plugins/tabfocus'
import 'tinymce/plugins/table'
import 'tinymce/plugins/template'
import 'tinymce/plugins/textcolor'
import 'tinymce/plugins/textpattern'
import 'tinymce/plugins/visualblocks'
import 'tinymce/plugins/visualchars'
import 'tinymce/plugins/wordcount'
import 'tinymce-placeholder'

export default {
  name: 'Tinymce',
  props: {
    id: {
      type: String,
      default: function() {
        return 'vue-tinymce-' + +new Date() + ((Math.random() * 1000).toFixed(0) + '')
      }
    },
    value: {
      type: String,
      default: ''
    },
    toolbar: {
      type: Array,
      required: false,
      default() {
        return []
      }
    },
    menubar: {
      type: String,
      default: 'file edit insert view format table'
    },
    height: {
      type: [Number, String],
      required: false,
      default: '100%'
    },
    width: {
      type: [Number, String],
      required: false,
      default: 'auto'
    },
    placeholder: {
      type: [String],
      required: false,
      default: ''
    }
  },
  data() {
    return {
      hasChange: false,
      hasInit: false,
      tinymceId: this.id,
      fullscreen: false,
      publicPath: process.env.BASE_URL
    }
  },
  computed: {
    containerWidth() {
      const width = this.width
      if (/^[\d]+(\.[\d]+)?$/.test(width)) { // matches `100`, `'100'`
        return `${width}px`
      }
      return width
    }
  },
  watch: {
    value(val) {
      if (!this.hasChange && this.hasInit) {
        this.$nextTick(() => tinymce.get(this.tinymceId).setContent(val || ''))
      }
    }
  },
  mounted() {
    this.init()
  },
  activated() {
    if (tinymce) {
      this.initTinymce()
    }
  },
  deactivated() {
    this.destroyTinymce()
  },
  destroyed() {
    this.destroyTinymce()
  },
  methods: {
    init() {
      window.tinymce.baseURL = `${this.publicPath}lib/tinymce`
      this.initTinymce()
    },
    initTinymce() {
      const _this = this
      tinymce.init({
        selector: `#${this.tinymceId}`,
        language_url: `${this.publicPath}lib/tinymce/langs/zh_CN.js`,
        language: 'zh_CN',
        deprecation_warnings: false,
        height: this.height,
        body_class: 'panel-body ',
        object_resizing: false,
        toolbar: this.toolbar.length > 0 ? this.toolbar : toolbar,
        menubar: this.menubar,
        placeholder: this.placeholder,
        plugins: plugins,
        end_container_on_empty_block: true,
        powerpaste_word_import: 'clean',
        code_dialog_height: 450,
        code_dialog_width: 1000,
        advlist_bullet_styles: 'square',
        advlist_number_styles: 'default',
        imagetools_cors_hosts: ['www.tinymce.com', 'codepen.io'],
        default_link_target: '_blank',
        link_title: false,
        nonbreaking_force_tab: true, // inserting nonbreaking space &nbsp; need Nonbreaking Space Plugin

        init_instance_callback: editor => {
          if (_this.value) {
            editor.setContent(_this.value)
          }
          _this.hasInit = true
          editor.on('NodeChange Change KeyUp SetContent', () => {
            this.hasChange = true
            this.$emit('input', editor.getContent())
          })
        },
        setup(editor) {
          editor.on('FullscreenStateChanged', (e) => {
            _this.fullscreen = e.state
          })
        },
        convert_urls: false,
        file_picker_types: 'media',
        // 本地视频上传
        file_picker_callback(cb, value, meta) {
          if (meta.filetype == 'media') {
            const input = document.createElement('input')
            input.setAttribute('type', 'file')
            input.onchange = function() {
              const fileObj = this.files[0]// 只选取第一个文件。如果要选取全部，后面注意做修改
              if (fileObj == undefined) {
                return _this.$message.error('请选择视频文件')
              }
              if (fileObj.size >= 10 * 1024 * 1024) {
                return _this.$message.error('到需要小于10MB!')
              }
              if (fileObj.type.indexOf('video') == -1) {
                return _this.$message.error('不是有效的视频文件!')
              }
              const vPar = new ParamArr()
              vPar.setStr('ID', _this.id)
              vPar.setStr('FileName', fileObj.name)
              RPAAddCommunityFile(vPar, fileObj).then(vPar => {
                const ServerFile = vPar.getStr('ServerFile')
                const fileUrl = fileHostUrl + '/' + ServerFile
                cb(fileUrl, { title: fileObj.name })
              }).catch(err => {
                console.log(err)
              })
            }
            // 触发点击
            input.click()
          }
        },
        // 本地图片上传
        images_upload_handler(blobInfo, success, failure, progress) {
          // progress(0)
          // 自定义图片上传
          // console.log('blobInfo')
          // console.log('id:', blobInfo.id())
          // console.log('name:', blobInfo.name())
          // console.log('uri:', blobInfo.uri())
          // console.log('base64:', blobInfo.base64())
          // console.log('blobUri:', blobInfo.blob())
          // console.log('blobUri:', blobInfo.blobUri())
          // console.log('filename:', blobInfo.filename())

          // base64转blob
          const base64ToBlob = function(base64Data) {
            const arr = base64Data.split(',')
            const fileType = arr[0].match(/:(.*?);/)[1]
            const bstr = atob(arr[1])
            let l = bstr.length
            const u8Arr = new Uint8Array(l)

            while (l--) {
              u8Arr[l] = bstr.charCodeAt(l)
            }
            return new Blob([u8Arr], {
              type: fileType
            })
          }
          // blob转file
          const blobToFile = function(newBlob, fileName) {
            newBlob.lastModifiedDate = new Date()
            newBlob.name = fileName
            return newBlob
          }
          const fileBlob = base64ToBlob('data:image/png;base64,' + blobInfo.base64())
          const temFile = blobToFile(fileBlob, blobInfo.filename())

          const fileObj = blobInfo.blob()
          if (fileObj == undefined) {
            return this.$message.error('请选择图片')
          }
          if (fileObj.size >= 2 * 1024 * 1024) {
            return this.$message.error('到需要小于2MB!')
          }
          if (fileObj.type.indexOf('image') == -1) {
            return this.$message.error('不是有效的图片文件!')
          }
          const vPar = new ParamArr()
          vPar.setStr('ID', _this.id)
          vPar.setStr('FileName', temFile.name)
          RPAAddCommunityFile(vPar, temFile).then(vPar => {
            const ServerFile = vPar.getStr('ServerFile')
            const imgUrl = fileHostUrl + '/' + ServerFile
            success(imgUrl)
          }).catch(err => {
            console.log(err)
          })
          // progress(100)
        }
      })
    },
    destroyTinymce() {
      const tinymceObj = tinymce.get(this.tinymceId)
      if (this.fullscreen) {
        tinymceObj.execCommand('mceFullScreen')
      }

      if (tinymceObj) {
        tinymceObj.destroy()
      }
    },
    setContent(value) {
      tinymce.get(this.tinymceId).setContent(value)
    },
    getContent() {
      tinymce.get(this.tinymceId).getContent()
    },
    imageSuccessCBK(arr) {
      arr.forEach(v => tinymce.get(this.tinymceId).insertContent(`<img class="wscnph" src="${v.url}" >`))
    }
  }
}
</script>
<style lang="scss" scoped>
.tinymce-container {
  height: 100%;
  position: relative;
  line-height: normal;
}

.tinymce-container {
  ::v-deep {
    .mce-fullscreen {
      z-index: 10000;
    }
  }
}

.tinymce-textarea {
  visibility: hidden;
  z-index: -1;
}

.editor-custom-btn-container {
  position: absolute;
  right: 4px;
  top: 4px;
  /*z-index: 2005;*/
}

.fullscreen .editor-custom-btn-container {
  z-index: 10000;
  position: fixed;
}

.editor-upload-btn {
  display: inline-block;
}

</style>
